package com.campus.food.service.impl;

import com.campus.food.mapper.OrderMapper;
import com.campus.food.mapper.OrderDetailMapper;
import com.campus.food.mapper.UserMapper;
import com.campus.food.mapper.MerchantMapper;
import com.campus.food.mapper.CartMapper;
import com.campus.food.mapper.FoodMapper;
import com.campus.food.mapper.AddressMapper;
import com.campus.food.model.entity.Order;
import com.campus.food.model.entity.OrderDetail;
import com.campus.food.model.entity.User;
import com.campus.food.model.entity.Merchant;
import com.campus.food.model.entity.Cart;
import com.campus.food.model.entity.Food;
import com.campus.food.model.entity.Address;
import com.campus.food.service.OrderService;
import com.campus.food.service.OrderDetailService;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private MerchantMapper merchantMapper;
    
    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private FoodMapper foodMapper;
    
    @Autowired
    private AddressMapper addressMapper;
    
    @Autowired
    private OrderDetailService orderDetailService;
    
    // 原子计数器用于生成订单号
    private static final AtomicLong orderSequence = new AtomicLong(1);
    
    @Override
    public Order createOrder(Order order) {
        // 验证订单信息
//        validateOrder(order);
        
        // 检查用户是否存在
        User user = userMapper.selectById(order.getUserId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查商家是否存在且营业中
        Merchant merchant = merchantMapper.selectById(order.getMerchantId());
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        if (merchant.getStatus() != 1) {
            throw new BusinessException("商家未通过审核");
        }
        
        if (merchant.getBusinessStatus() != 1) {
            throw new BusinessException("商家暂停营业");
        }
        
        // 检查地址是否存在
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new BusinessException("配送地址不存在");
        }
        
        // 生成订单号
        order.setOrderNo(generateOrderNo());
        
        // 设置订单初始状态
        order.setStatus(0);  // 待付款
        
        // 计算订单总金额（这里应该根据购物车商品计算，简化处理）
        if (order.getTotalPrice() == null) {
            throw new BusinessException("订单总金额不能为空");
        }
        
        // 保存订单
        int result = orderMapper.insert(order);
        if (result <= 0) {
            throw new BusinessException("创建订单失败");
        }
        
        // 保存订单明细
        if (order.getOrderDetails() != null && !order.getOrderDetails().isEmpty()) {
            for (OrderDetail detail : order.getOrderDetails()) {
                detail.setOrderId(order.getId()); // 设置订单ID
                orderDetailMapper.insert(detail);
            }
        }
        
        return order;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Order getOrderById(Long id) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 获取订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        order.setOrderDetails(orderDetails);
        
        // 获取配送地址信息
        if (order.getAddressId() != null) {
            Address address = addressMapper.selectById(order.getAddressId());
            if (address != null) {
                order.setDeliveryAddress(address.getDetailAddress());
//                order.setReceiverName(address.getReceiver());
//                order.setReceiverPhone(address.getPhone());
            }
        }
        
        return order;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Order getOrderByOrderNo(String orderNo) {
        if (!StringUtils.hasText(orderNo)) {
            throw new BusinessException("订单号不能为空");
        }
        
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 获取订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
        order.setOrderDetails(orderDetails);
        
        // 获取配送地址信息
        if (order.getAddressId() != null) {
            Address address = addressMapper.selectById(order.getAddressId());
            if (address != null) {
                order.setDeliveryAddress(address.getDetailAddress());
                order.setReceiverName(address.getReceiver());
                order.setReceiverPhone(address.getPhone());
            }
        }
        
        return order;
    }
    
    @Override
    public boolean updateOrder(Order order) {
        if (order.getId() == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        // 检查订单是否存在
        Order existingOrder = orderMapper.selectById(order.getId());
        if (existingOrder == null) {
            throw new BusinessException("订单不存在");
        }
        
        return orderMapper.updateById(order) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateOrderStatus(Long id, Integer status) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (status == null) {
            throw new BusinessException("订单状态不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 验证状态流转的合法性
        validateStatusTransition(order.getStatus(), status);
        orderMapper.updateStatus(id, status);
        if (status == 3){
            orderMapper.updateDeliveryTime(id, LocalDateTime.now());
        }

        if (status == 4){
            Long orderId = order.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
            int sum = 0;
            for (OrderDetail detail : orderDetails) {
                Long foodId = detail.getFoodId();
                foodMapper.increaseSales(foodId,detail.getQuantity());
                sum+=detail.getQuantity();
            }
            Long merchantId = order.getMerchantId();
            Merchant merchant = merchantMapper.selectById(merchantId);
            merchant.setMonthlySales(merchant.getMonthlySales()==null?0:merchant.getMonthlySales()+sum);
            merchantMapper.updateById(merchant);
            orderMapper.updateCompleteTime(id, LocalDateTime.now());
        }


        return true;
    }
    
    @Override
    public boolean payOrder(Long id, Integer paymentMethod) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (paymentMethod == null) {
            throw new BusinessException("支付方式不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查订单状态
        if (order.getStatus() != 0) {
            throw new BusinessException("订单状态不正确，无法支付");
        }
        
        // 更新支付信息
        boolean paymentResult = orderMapper.updatePayment(id, paymentMethod, LocalDateTime.now()) > 0;
        
        // if (paymentResult) {
        //     // 增加商品销量
        //     List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        //     for (OrderDetail detail : orderDetails) {
        //         foodMapper.increaseSales(detail.getFoodId(), detail.getQuantity());
        //     }
        // }
        
        return paymentResult;
    }
    
    @Override
    public boolean confirmOrder(Long id, Long merchantId) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 验证权限
        if (!order.getMerchantId().equals(merchantId)) {
            throw new BusinessException("无权限操作此订单");
        }
        
        // 检查订单状态
        if (order.getStatus() != 1) {
            throw new BusinessException("订单状态不正确，无法确认");
        }
        
        return orderMapper.updateStatus(id, 2) > 0;
    }
    
    @Override
    public boolean startDelivery(Long id, Long merchantId) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 验证权限
        if (!order.getMerchantId().equals(merchantId)) {
            throw new BusinessException("无权限操作此订单");
        }
        
        // 检查订单状态
        if (order.getStatus() != 2) {
            throw new BusinessException("订单状态不正确，无法开始配送");
        }
        
        // 更新配送时间和状态（XML中已自动更新状态为3）
        return orderMapper.updateDeliveryTime(id, LocalDateTime.now()) > 0;
    }
    
    @Override
    public boolean completeOrder(Long id, Long userId) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 验证权限
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权限操作此订单");
        }
        
        // 检查订单状态
        if (order.getStatus() != 3) {
            throw new BusinessException("订单状态不正确，无法确认收货");
        }
        
        // 更新完成时间和状态（XML中已自动更新状态为4）
        return orderMapper.updateCompleteTime(id, LocalDateTime.now()) > 0;
    }
    
    @Override
    public boolean cancelOrder(Long id, String cancelReason, Long operatorId) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (!StringUtils.hasText(cancelReason)) {
            throw new BusinessException("取消原因不能为空");
        }
        
        if (operatorId == null) {
            throw new BusinessException("操作者ID不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查是否可以取消
        if (!canCancelOrder(id)) {
            throw new BusinessException("订单当前状态不允许取消");
        }
        
        return orderMapper.cancelOrder(id, cancelReason, LocalDateTime.now()) > 0;
    }
    
    @Override
    public boolean deleteOrder(Long id) {
        if (id == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 先删除订单详情
        orderDetailMapper.deleteByOrderId(id);
        
        // 再删除订单
        return orderMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Order> getUserOrders(Long userId, int page, int size, Integer status) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        int offset = (page - 1) * size;
        List<Order> orders = orderMapper.selectPageByUser(userId, offset, size, status);
        
        // 为每个订单加载详情和地址信息
        for (Order order : orders) {
            loadOrderDetailsAndAddress(order);
        }
        
        return orders;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getUserOrderCount(Long userId, Integer status) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        Long count = orderMapper.selectCountByUser(userId, status);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Order> getMerchantOrders(Long merchantId, int page, int size, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        int offset = (page - 1) * size;
        List<Order> orders = orderMapper.selectPageByMerchant(merchantId, offset, size, status);
        
        // 为每个订单加载详情和地址信息
        for (Order order : orders) {
            loadOrderDetailsAndAddress(order);
        }
        
        return orders;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getMerchantOrderCount(Long merchantId, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        Long count = orderMapper.selectCountByMerchant(merchantId, status);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Order> getAllOrders(int page, int size, String orderNo, Integer status, LocalDateTime startTime, LocalDateTime endTime) {
        int offset = (page - 1) * size;
        List<Order> orders = orderMapper.selectPageForAdmin(offset, size, orderNo, status, startTime, endTime);
        
        // 为每个订单加载详情和地址信息
        for (Order order : orders) {
            loadOrderDetailsAndAddress(order);
        }
        
        return orders;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getAllOrderCount(String orderNo, Integer status, LocalDateTime startTime, LocalDateTime endTime) {
        Long count = orderMapper.selectCountForAdmin(orderNo, status, startTime, endTime);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Order> getOrdersByStatus(Integer status) {
        List<Order> orders = orderMapper.selectByStatus(status);
        
        // 为每个订单加载详情和地址信息
        for (Order order : orders) {
            loadOrderDetailsAndAddress(order);
        }
        
        return orders;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getUserOrderCountByMerchant(Long userId, Long merchantId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        Long count = orderMapper.selectCountByUserAndMerchant(userId, merchantId);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getOrderCountByTimeRange(LocalDateTime startTime, LocalDateTime endTime, Integer status) {
        if (startTime == null || endTime == null) {
            throw new BusinessException("时间范围不能为空");
        }
        
        Long count = orderMapper.selectCountByTimeRange(startTime, endTime, status);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Double getSalesAmountByTimeRange(LocalDateTime startTime, LocalDateTime endTime, Integer status) {
        if (startTime == null || endTime == null) {
            throw new BusinessException("时间范围不能为空");
        }
        
        Double amount = orderMapper.selectSalesAmountByTimeRange(startTime, endTime, status);
        return amount != null ? amount : 0.0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getMerchantOrderCountByTimeRange(Long merchantId, LocalDateTime startTime, LocalDateTime endTime, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (startTime == null || endTime == null) {
            throw new BusinessException("时间范围不能为空");
        }
        
        Long count = orderMapper.selectCountByMerchantAndTimeRange(merchantId, startTime, endTime, status);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Double getMerchantSalesAmountByTimeRange(Long merchantId, LocalDateTime startTime, LocalDateTime endTime, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (startTime == null || endTime == null) {
            throw new BusinessException("时间范围不能为空");
        }
        
        Double amount = orderMapper.selectSalesAmountByMerchantAndTimeRange(merchantId, startTime, endTime, status);
        return amount != null ? amount : 0.0;
    }
    
    @Override
    public String generateOrderNo() {
        // 生成订单号格式：年月日时分秒 + 6位递增序列号
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        long sequence = orderSequence.getAndIncrement() % 1000000; // 保证6位数
        return timestamp + String.format("%06d", sequence);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean canCancelOrder(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return false;
        }
        
        // 只有待支付、待接单、备餐中的订单可以取消
        Integer status = order.getStatus();
        return status == 0 || status == 1 || status == 2;
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean canRefundOrder(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return false;
        }
        
        // 只有已支付但未完成的订单可以退款
        return order.getPaymentTime() != null && 
               (order.getStatus() == 1 || order.getStatus() == 2);
    }
    
    /**
     * 为订单加载详情和地址信息
     */
    private void loadOrderDetailsAndAddress(Order order) {
        if (order == null) {
            return;
        }
        
        // 加载订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
        order.setOrderDetails(orderDetails);
        
        // 加载地址信息
        if (order.getAddressId() != null) {
            Address address = addressMapper.selectById(order.getAddressId());
            if (address != null) {
                order.setDeliveryAddress(address.getDetailAddress());
                order.setReceiverName(address.getReceiver());
                order.setReceiverPhone(address.getPhone());
            }
        }
        
        // 计算实际支付金额（这里可以根据业务逻辑计算折扣等）
        // 默认情况下与总价相同
        if (order.getTotalPrice() != null) {
            order.setActualAmount(order.getTotalPrice());
        }
    }
    
    /**
     * 验证订单信息
     */
    private void validateOrder(Order order) {
        if (order == null) {
            throw new BusinessException("订单信息不能为空");
        }
        
        if (order.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (order.getMerchantId() == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (order.getAddressId() == null) {
            throw new BusinessException("地址ID不能为空");
        }
        
        if (order.getTotalPrice() == null || order.getTotalPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("订单总金额必须大于0");
        }
    }
    
    /**
     * 验证状态流转的合法性
     */
    private void validateStatusTransition(Integer currentStatus, Integer newStatus) {
        // 定义合法的状态流转
        if (currentStatus == 0) { // 待付款
            if (newStatus != 1 && newStatus != 5) {
                throw new BusinessException("待付款订单只能转换为待接单或已取消状态");
            }
        } else if (currentStatus == 1) { // 待接单
            if (newStatus != 2 && newStatus != 5) {
                throw new BusinessException("待接单订单只能转换为备餐中或已取消状态");
            }
        } else if (currentStatus == 2) { // 备餐中
            if (newStatus != 3 && newStatus != 5) {
                throw new BusinessException("备餐中订单只能转换为配送中或已取消状态");
            }
        } else if (currentStatus == 3) { // 配送中
            if (newStatus != 4) {
                throw new BusinessException("配送中订单只能转换为已完成状态");
            }
        } else if (currentStatus == 4 || currentStatus == 5) { // 已完成或已取消
            throw new BusinessException("已完成或已取消的订单不能再次修改状态");
        }
    }
} 